﻿using System.Linq;
using Contrib.Chapters.Services;
using JetBrains.Annotations;
using Orchard.ContentManagement.Drivers;
using Contrib.Chapters.Models;

namespace Contrib.Chapters.Drivers {
    [UsedImplicitly]
    public class BookPartDriver : ContentPartDriver<BookPart> {
        private readonly IChapterService _chapterService;

        public BookPartDriver(IChapterService chapterService) {
            _chapterService = chapterService;
        }

        protected override string Prefix { get { return "Book"; } }

        protected override DriverResult Display(BookPart part, string displayType, dynamic shapeHelper) {
            var chapters = _chapterService.GetChapters(part).Select((c, i) => new { Chapter = c, Index = i }).ToList();

            return Combined(
                ContentShape("Parts_Chapters_Navigation",
                    () => {
                        var next = chapters.Where(c => c.Index == 0).Select(c => c.Chapter).FirstOrDefault();
                        return shapeHelper.Parts_Chapters_Navigation(ContentPart: part, Next: next, Previous: null, Parent: null);
                    }),
                ContentShape("Parts_Chapters_Sections",
                    () => {
                        var sections = chapters.Where(c => c.Chapter.Level == 0).Select(c => c.Chapter);
                        return shapeHelper.Parts_Chapters_Sections(ContentPart: part, Sections: sections);
                    })
                );
        }

    }
}